﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using DTC.Database;

namespace DTC.Popups
{
    /// <summary>
    /// Interaction logic for DoctorPopup.xaml
    /// </summary>
    public partial class DoctorPopup : Window
    {
        public DoctorPopup()
        {
            InitializeComponent();
            this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            doctor = new DTCDoctor();
            MainStackPanel.DataContext = doctor;
            specializations = ReadSpecializations();
            SpecialComboBox.ItemsSource = specializations;
            isNew = true;
        }

        bool isNew;

        private ObservableCollection<DTCSpecialization> specializations;
        private ObservableCollection<DTCSpecialization> ReadSpecializations()
        {
            return new ObservableCollection<DTCSpecialization>(App.DBI.GetAllSpecializations());
        }

        private DTCDoctor doctor;
        public DTCDoctor Doctor
        {
            get
            {
                return doctor;
            }
            set
            {
                doctor = value;
                //StoredDoctor = value;
                MainStackPanel.DataContext = doctor;
                isNew = false;
                SetSpecialComboBox();
            }
        }

        public string FullName
        {
            get
            {
                return doctor.FullName;
            }
            set
            {
                string[] names = value.Split(new Char[] { ' ' });
                doctor.Surname = names[0];
                if (names.Length > 1)
                    doctor.Name = names[1];
                if (names.Length > 2)
                    doctor.Fathername = names[2];
            }
        }

        private void SetSpecialComboBox()
        {
            int i = 0;
            foreach(DTCSpecialization sp in specializations)
            {
                if(doctor.SpecializationID == sp.SpecializationID)
                {
                    SpecialComboBox.SelectedIndex = i;
                    return;
                }
                i++;
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if(this.DialogResult == true)
            {
                string WarningMessage = "Необходимо указать следующие данные:\n";
                bool flag=false;
                if(SurnameTextBox.Text.Length == 0)
                {
                    WarningMessage += "Фамилия\n";
                    flag = true;
                }
                if(NameTextBox.Text.Length == 0)
                {
                    WarningMessage += "Имя\n";
                    flag = true;
                }
                if(flag)//если найдены неполадки
                {
                    e.Cancel = true;
                    WarningPopup wp = new WarningPopup();
                    wp.Owner = this;
                    wp.Message = WarningMessage;
                    wp.Title = "Не полная информация";
                    wp.ShowDialog();
                    e.Cancel = true;
                    return;
                }
                else //все хорошо, можно сохранять в БД
                {
                    bool WasUpdated = false;
                    if (SurnameTextBox.Text != doctor.Surname)
                    {
                        doctor.Surname = SurnameTextBox.Text;
                        WasUpdated = true;
                    }
                    if (NameTextBox.Text != doctor.Name)
                    {
                        doctor.Name = NameTextBox.Text;
                        WasUpdated = true;
                    }
                    if (FathernameTextBox.Text != doctor.Fathername)
                    {
                        doctor.Fathername = FathernameTextBox.Text;
                        WasUpdated = true;
                    }
                    if (SpecialComboBox.SelectedIndex == -1 && SpecialComboBox.Text.Length != 0)
                    {
                        DTCSpecialization newSpec = new DTCSpecialization();
                        newSpec.Name = SpecialComboBox.Text;
                        newSpec.Insert();
                        doctor.DTCSpecialization = newSpec;
                        WasUpdated = true;
                    }
                    else if (SpecialComboBox.SelectedIndex != -1)
                    {
                        DTCSpecialization newSpec = (DTCSpecialization)SpecialComboBox.SelectedItem;
                        bool doIt = false;
                        if (doctor.DTCSpecialization == null)
                            doIt = true;
                        else if (doctor.DTCSpecialization != newSpec)
                            doIt = true;
                        if (doIt)
                        {
                            doctor.DTCSpecialization = newSpec;
                            WasUpdated = true;
                        }
                    }

                    if (isNew)
                        doctor.Insert();
                    else if(WasUpdated == true)
                    {
                        doctor.Update();
                    }
                }
            }

                
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            PrepareBindings(MainStackPanel);
        }

        private void PrepareBindings(FrameworkElement Container)
        {
            BindingExpression expression;
            TextBox tmp;
            foreach (object child in LogicalTreeHelper.GetChildren(Container))
            {
                if (child is TextBox)
                {
                    tmp = child as TextBox;
                    expression = tmp.GetBindingExpression(TextBox.TextProperty);
                    if (expression != null)
                    {
                        expression.UpdateSource();
                    }
                }
                else
                {
                    if (child is FrameworkElement)
                        PrepareBindings(child as FrameworkElement);
                }
            }
        }
    }
}
